package com.src.xyzk_personal;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.src.tsdl_personal.R;
import com.src.xyzk_personal.config.ComSocket;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.Commonfunc;
import com.src.xyzk_personal.config.ServerSocket;
import com.src.xyzk_personal.config.WifiAdmin;

public class ConnectWifiDialog {
	private final static String TAG = "ConnectWifiDialog";
	private Dialog alertDialog;
	private ViewGroup alertViewGroup;
	private Activity myactivity = null;
	private int width = 0;
	private Button m_onok = null;
	private Button m_manual = null;	//手动连接按钮
	private Button m_close = null;	//关闭窗口
	private int m_object = 0;	//目标网络
	private boolean threadexit = false;
	private int m_isconnected = 0;   //0--未连接，1-- 已经连接到一个网络; 2--连接到正确的网络
	ContentValues m_uptbmain = null;
	ArrayList<Map<String, String>> m_uplist = null;
	ArrayList<Map<String, String>> m_uplisthide = null;  //隐藏列表
	private String m_serialnum = null;
	public ConnectWifiDialog(Activity activity) {
		// TODO Auto-generated constructor stub
		this.myactivity = activity;
		WindowManager manager = activity.getWindowManager();
		Display display = manager.getDefaultDisplay();
		width = display.getWidth() - 30;
		LayoutInflater inflater = activity.getLayoutInflater();
		alertViewGroup = (ViewGroup) inflater.inflate(R.layout.connnect_dialog, null);
		//alertDialog = new Dialog.Builder(activity).create();
		//alertDialog = new AlertDialog.Builder(activity).create();
		alertDialog = new Dialog(activity);
		//alertDialog.setTitle(R.string.msg_wait_title);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if(Common.Debug) Log.i(TAG,"创建窗口!");
		if(alertDialog != null)
			alertDialog.show();
		//处理确定按钮
		m_onok = (Button)alertViewGroup.findViewById(R.id.connect_dialog_but_ok);
		m_onok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dismiss();
			}
		});
		m_manual = (Button)alertViewGroup.findViewById(R.id.connect_dialog_connect);
		m_manual.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SetAutoConnect(m_object);
			}
		});
		//close
		m_close = (Button)alertViewGroup.findViewById(R.id.connect_dialog_close);
		m_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
				threadexit = true;
			}
		});
		//屏蔽返回
		alertDialog.setCancelable(false);
	}
	public void setOnKeyListener(DialogInterface.OnKeyListener keyListener)
	{
		alertDialog.setOnKeyListener(keyListener);
	}
	public ConnectWifiDialog setPositiveButton(String buttonText,OnClickListener l){
		Button positiveButton = (Button)alertViewGroup.findViewById(R.id.connect_dialog_but_ok);
		positiveButton.setOnClickListener(l);
		//positiveButton.setText(buttonText);
		//alertViewGroup.findViewById(R.id.input_vin_but_ok).setVisibility(View.VISIBLE);
		return this;
	}
	//上传数据
	public void SetUpdateData(ContentValues tbmain,ArrayList<Map<String, String>> list,ArrayList<Map<String, String>> listhide)
	{
		m_uptbmain = tbmain;
		m_uplist = list;
		m_uplisthide = listhide;
	}
	//设置自动连接
	//object:1 --- 连服务器;2 --- 连BOX.
	public void SetAutoConnect(int object)
	{
		//禁用按钮
		m_onok.setClickable(false);
		m_onok.setText(R.string.but_waitting);
		m_object = object;
		if(m_object == 1) //服务器
			mhandler.obtainMessage(MSG_ShowText, "连接到【服务器】网络...").sendToTarget();
		else if(m_object == 2) //box
			mhandler.obtainMessage(MSG_ShowText, "连接到【诊断接头】...").sendToTarget();
		final WifiAdmin m_wifi = new WifiAdmin(myactivity);
		if(m_wifi.getState() < 2) //已经关闭，则打开
		{
			m_wifi.openWifi();
			while(true)
			{
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(m_wifi.getState() >= 2) break;
				if(threadexit) return;
			}
			Sleep(1000); //这里延迟一下
		}
		//获取当前连接状态
		String ConnectName = m_wifi.getWifiConnectSSID();
		if(Common.Debug) Log.i(TAG,"WIFI连接情况,已连接-->" + ConnectName);
		//查看连接状态，如果未连接则连接,如果已经连接，则使用当前网络
		if(ConnectName.length() > 3) //已经连接到一个网络
			m_isconnected = 1; //已经连接到一个网络
		if(m_object == 1) //连接服务器
		{
			if(ConnectName.equals(Common.ServerName) == true) //相同，已经连接
				m_isconnected = 2;
		}
		else if(m_object == 2) //连接box
		{
			if(ConnectName.equals(Common.BoxName) == true) //相同，已经连接
				m_isconnected = 2;
		}
		if(m_isconnected < 2) //未连接到正确的网络，则开始扫描
			m_wifi.startScan();
		if(threadexit) return;
		//开始倒计时
		new Thread()
		{
			@Override
			public void run() {
				// TODO Auto-generated method stub
				int i,iRet = 0;
				if(m_isconnected < 2) //未连接到正确的网络
				{
					//线断开之前连接的网络
					if(threadexit) return;
					m_wifi.DisConnect();
					Sleep(1000);
					if(threadexit) return;
				}
				for(i = 0; i < Common.cmd_freq; i ++)
				{
					if(Common.Debug) Log.i(TAG,"正在连接网络:" + m_object);
					if(m_object == 1) //连服务器
					{
						iRet = m_wifi.ConnectServer(Common.ServerName);
					}
					else if(m_object == 2) //连BOX
					{
						iRet = m_wifi.ConnectBox(Common.BoxName);
					}
					if(iRet > 0)
						break;
					if(threadexit) return;
					Sleep(500);
					if(Common.Debug) Log.i(TAG,"连接失败,iRet=" + iRet);
				}
				if(i >= Common.cmd_freq) //连接失败，显示原因
				{
					if(iRet == -1) //没有搜索到网络
					{
						if(m_object == 1) //服务器
							mhandler.obtainMessage(MSG_ShowText, "未搜索到【服务器】网络信号，请确认后，手动连接!").sendToTarget();
						else if(m_object == 2) //box
							mhandler.obtainMessage(MSG_ShowText, "未搜索到【诊断接头】，请确认【诊断接头】已连接，并点击手动连接！").sendToTarget();
					}
					else
					{
						if(m_object == 1) //服务器
							mhandler.obtainMessage(MSG_ShowText, "【服务器】网络连接失败!请检查网络，并手动连接!").sendToTarget();
						else if(m_object == 2) //box
							mhandler.obtainMessage(MSG_ShowText, "【诊断接头】连接失败!请确认【诊断接头】已连接，并点击手动连接！").sendToTarget();
					}
					mhandler.obtainMessage(MSG_SHOW_MANUALBUTTON).sendToTarget();
					return;
				}
				//这里不停的检查连接情况,用户体验会比较好
				String ObjectName = null;
				if(m_object == 1) //server
					ObjectName = Common.ServerName;
				else if(m_object == 2) //box
					ObjectName = Common.BoxName;
				while(true)
				{
					Sleep(200);//延迟
					String connectname = m_wifi.getWifiConnectSSID();
					if(Common.Debug) Log.i(TAG,"Wifi Connect: " + connectname);
					if(ObjectName.equals(connectname) == true) //连接成功
						break;
					if(threadexit) return;
				}
				if(m_object == 1) //服务器，上传数据
				{
					mhandler.obtainMessage(MSG_ShowText, "正在建立Socket连接...").sendToTarget();
					Sleep(500);
					if(threadexit) return;
					ServerSocket m_server = new ServerSocket();
					if(m_server.ConnectServer(Common.Server_IP, Common.Server_PORT))
					{
						mhandler.obtainMessage(MSG_ShowText, "连接成功！正在发送数据...").sendToTarget();
						//发送数据
						String data;
						if(m_uptbmain != null)
							data = m_uptbmain.toString();
						else
							data = null;
						if(m_server.SendDataToServer("1:" + data))
						{
							mhandler.obtainMessage(MSG_ShowText, "主表上传成功!").sendToTarget();
						}
						else
						{
							mhandler.obtainMessage(MSG_ShowText, "主表上传失败!").sendToTarget();
						}
						Sleep(10);
						int record = 0;
						if(m_uplist != null)
						{
							for(i = 0; i <m_uplist.size(); i ++)
							{
								if(m_server.SendDataToServer("2:" + m_uplist.get(i).toString()))
								{
									mhandler.obtainMessage(MSG_ShowText, "上传数据表:" + i).sendToTarget();
								}
								else
								{
									mhandler.obtainMessage(MSG_ShowText, "数据表上传失败!").sendToTarget();
								}
								Sleep(2);
								record = i;
							}
							if(m_uplisthide != null)
							{
								for(i = 0; i <m_uplisthide.size(); i ++)
								{
									if(m_server.SendDataToServer("2:" + m_uplisthide.get(i).toString()))
									{
										mhandler.obtainMessage(MSG_ShowText, "上传数据表:" + (record + i)).sendToTarget();
									}
									else
									{
										mhandler.obtainMessage(MSG_ShowText, "数据表上传失败!").sendToTarget();
									}
									Sleep(2);
								}
							}
							mhandler.obtainMessage(MSG_ShowText, "数据表上传成功!").sendToTarget();
						}
						//退出连接
						if(m_server.SendDataToServer("3"))
						{
							mhandler.obtainMessage(MSG_ShowText, "退出成功!").sendToTarget();
							mhandler.obtainMessage(MSG_Enable_button).sendToTarget();
						}
						else
						{
							mhandler.obtainMessage(MSG_ShowText, "退出失败!").sendToTarget();
						}
					}
					else
					{
						mhandler.obtainMessage(MSG_ShowText, "连接失败!请手动连接...").sendToTarget();
						mhandler.obtainMessage(MSG_SHOW_MANUALBUTTON).sendToTarget();
					}
					m_server.close();
				}
				else if(m_object == 2) //接头，则读出序列号
				{
					mhandler.obtainMessage(MSG_ShowText, "连接成功！正在验证序列号...").sendToTarget();
					Sleep(500);
					if(threadexit) return;
					ComSocket m_com = null;
					m_com = new ComSocket();
					if(m_com.ConnectBox(Common.BoxIP, Common.BoxPORT))
					{
					}
					else
					{
						if(Common.Debug) Log.i(TAG,"Socket 连接失败!");
					}
					if(threadexit) return;
					Sleep(200);
					byte[] serialnum = new byte[12];
					byte[] softv = new byte[2];
					for(i = 0; i < Common.cmd_freq; i ++)
					{
						if(m_com.GetSerialNum(serialnum, serialnum.length,softv)) break;
						Sleep(50);
						if(threadexit) return;
					}
					if(i >= Common.cmd_freq)
					{
						mhandler.obtainMessage(MSG_ShowText, "获取序列号失败,请点击【手动连接】!").sendToTarget();
						mhandler.obtainMessage(MSG_SHOW_MANUALBUTTON).sendToTarget();
					}
					else
					{
						if(Common.Debug) Log.i(TAG,"读序列号成功:" + new String(serialnum));
						mhandler.obtainMessage(MSG_ShowText, "Box版本:V" + Commonfunc.byteToHexString(softv[0])
								+ "." + Commonfunc.byteToHexString(softv[0]) +"\n" +
								"序列号:" + new String(serialnum)).sendToTarget();
						m_serialnum = new String(serialnum); //获取序列号
						mhandler.obtainMessage(MSG_Enable_button).sendToTarget();
					}
					m_com.close();
				}
				if(Common.Debug) Log.i(TAG,"线程结束");
			}

		}.start();

	}
	private void Sleep(int mtimes)
	{
		try {
			Thread.sleep(mtimes); //延时
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public ConnectWifiDialog setOnOKButton(OnClickListener l){
		//return setPositiveButton(activity.getResources().getString(resId),l);
		return setPositiveButton("",l);
	}
	public void cancel(){
		alertDialog.cancel();
	}

	public void dismiss(){
		alertDialog.dismiss();
	}
	public void show(){
		alertDialog.getWindow().setLayout(width, LayoutParams.WRAP_CONTENT);
		alertDialog.getWindow().setContentView(alertViewGroup);
	}
	//set title
	public ConnectWifiDialog setTitle(String title){
		//TextView titleView = (TextView)alertViewGroup.findViewById(R.id.msg_wait_title);
		//titleView.setText(title);
		alertDialog.setTitle(title);
		return this;
	}

	public ConnectWifiDialog setTitle(int resId){
		return setTitle(myactivity.getResources().getString(resId));
	}
	public void setText(String str)
	{
		TextView textView = (TextView)alertViewGroup.findViewById(R.id.connect_dialog_context);
		textView.setText(str);
	}
	public void setText(int resid)
	{
		TextView textView = (TextView)alertViewGroup.findViewById(R.id.connect_dialog_context);
		textView.setText(myactivity.getResources().getString(resid) );
	}
	public String getSerialNum()
	{
		return m_serialnum;
	}
	private final static int MSG_ShowText = 101;	//显示文本
	private final static int MSG_exit	= 102;		//退出
	private final static int MSG_Enable_button = 103;	//启用按钮
	private final static int MSG_SHOW_MANUALBUTTON = 104;	//显示重试按钮
	private final Handler mhandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what) {
				case MSG_ShowText:
//				m_onok.setText(myactivity.getResources().getString(R.string.msg_wait_dialog_text1) + msg.arg1 +
//						myactivity.getResources().getString(R.string.msg_wait_dialog_text2));
					setText((String)msg.obj);
					break;
				case MSG_exit:
					dismiss();
					break;
				case MSG_Enable_button:
					//禁用按钮
					m_onok.setClickable(true);
					m_onok.setText(R.string.but_ok);
					break;
				case MSG_SHOW_MANUALBUTTON:
					m_manual.setVisibility(View.VISIBLE);
					break;
				default:
					break;
			}
		};
	};
}
